import { defineStore } from "pinia";
import { POST } from "@/utils";
import EventBus from "@/utils/EventBus";


const getAllDeviceApi = () => POST('/queryAllDevice', null, false)
const getAllDepartmentApi = () => POST('/queryDepartment', {}, false)
const getAllAreaApi = () => POST('/queryIllArea', {}, false)
const getAllVersionApi = () => POST('/selectVersion', {}, false)
const getAllDeviceTypeApi = () => POST('/selectDeviceType', {}, false)

export interface StringOption {
    value: string,
    label: string
}

export interface NumberOption {
    value: string,
    label: number
}



export const useCommon = defineStore('common', {
    state: () => {
        return {
            showSearch: true,
            selectedKeys: ['Device'],
            department: null as string | null,
            id: null as number | null,
            illArea: '' as string | null,
            deviceOptions: [] as StringOption[],
            deviceVersionOptions: [] as StringOption[],
            versionOptions: [] as StringOption[],


            SelfDeviceOptions: [] as StringOption[],
            FirstValueData: [] as NumberOption[],

            FirstData: [] as any[],
            SecondData: [] as any[],
            SecondLeafArr: [] as any[],
            ThirdData: [] as any[],
            ThirdLeafArr: [] as any[],
            currentPermissionLeafArr: [] as any[],

            deviceTypeOptions: [] as StringOption[],
        }
    },
    getters: {},
    actions: {
        setShowSearch(flag: boolean) {
            this.showSearch = flag
        },
        getDevicesOptions() {
            return this.deviceOptions
        },
        // 设置缓存
        async setUser(department: string | null, id: number | null, illArea: string | null,) {
            return new Promise((resolve, reject) => {
                this.department = department
                this.id = id
                this.illArea = illArea
                resolve('ok')
            })
        },
        // 版本
        async getVersion() {
            // console.log('getVersion');
            this.versionOptions = []
            const data = await getAllVersionApi() as any

            return new Promise((resolve, reject) => {
                if (data) {
                    data.forEach((item: any) => {
                        this.versionOptions.push({
                            label: `${item.deviceType}-(${item.versionId}版本)`,
                            value: item.download
                        })
                    })
                }
                resolve('ok')
            })
        },
        // 查询设备
        async getAllDevice() {
            this.ThirdData = []
            this.deviceOptions = []
            this.deviceVersionOptions = []
            this.SelfDeviceOptions = []
            const data = await getAllDeviceApi() as any
            return new Promise((resolve, reject) => {
                if (data) {
                    data.forEach((item: any) => {
                        this.deviceOptions.push({
                            label: `${item.deviceName}`,
                            value: item.serial
                        })
                        this.deviceVersionOptions.push({
                            label: `${item.deviceName}(${item.versionId}版本)`,
                            value: item.serial
                        })
                        this.ThirdData.push({
                            label: item.deviceName,
                            value: item.serial,
                            parent: item.illArea,
                            grandFather: item.department
                        })
                        if (item.department === this.department || this.department === '检验科') {
                            this.SelfDeviceOptions.push({
                                label: item.deviceName,
                                value: item.serial
                            })
                        }
                    })
                }
                resolve('getDevice ok')
            })
        },
        // 一级科室
        async getAllFirstData() {
            this.FirstData = []
            this.FirstValueData = []
            const data = await getAllDepartmentApi() as any
            if (data) {
                data.forEach((item: any) => {
                    this.FirstData.push({
                        label: item.department,
                        value: item.department
                    })
                    this.FirstValueData.push({
                        label: item.department,
                        value: item.id
                    })
                })
            }
        },
        // 二级病区
        async getAllSecondData() {
            this.SecondData = []
            const data = await getAllAreaApi() as any
            if (data) {
                data.forEach((item: any) => {
                    this.SecondData.push({
                        label: item.illArea,
                        value: item.illArea,
                        parent: item.department,
                    })
                })
            }
        },
        async handleSecondData() {
            this.SecondLeafArr = []
            return new Promise((resolve, reject) => {
                this.SecondLeafArr = this.FirstData.map(item => ({
                    label: item.label,
                    value: item.value,
                    children: this.SecondData.filter(second => second.parent == item.value)
                }))
                this.currentPermissionLeafArr = this.FirstData.filter(item => item.value == this.department).map(item => ({
                    ...item,
                    children: this.SecondData.filter(second => second.parent == item.value)
                }))
                resolve('second ok')
            })
        },
        // 三级设备
        async handleThirdData() {
            this.ThirdLeafArr = []
            return new Promise((resolve, reject) => {
                this.ThirdLeafArr = this.FirstData.map(item => ({
                    label: item.label,
                    value: item.value,
                    children: this.SecondData.filter(second => second.parent == item.value).map(second => {
                        return {
                            label: second.label,
                            value: second.value,
                            children: this.ThirdData.filter(third => third.parent == second.value && third.grandFather == item.value).map(third => ({ ...third }))
                        }
                    })
                }))
                resolve('third ok')
            })
        },
        // 设备类型
        async getDeviceType() {
            this.deviceTypeOptions = []
            try {
                const data = await getAllDeviceTypeApi() as any
                if (data) {
                    data.forEach((item: any) => {
                        this.deviceTypeOptions.push({
                            label: item.deviceType,
                            value: item.deviceType
                        })
                    })
                }
                return Promise.resolve('getDeviceType ok')
            } catch (err) {
                return Promise.reject(err)
            } finally { }
        },
        // 登陆成功查询数据
        async getData(department: string | null, id: number | null, illArea: string | null) {
            this.setUser(department, id, illArea)
                .then(res => {
                    this.getAllDevice()
                }).then(res => {
                    return Promise.all([this.getAllFirstData(), this.getAllSecondData()])
                }).then(() => {
                    return this.handleSecondData()
                }).then((res) => {
                    return this.handleThirdData()
                }).then(res => {
                    return this.getVersion()
                }).then(res => {
                    return this.getDeviceType()
                }).then(res => {
                    if (res) {
                        EventBus.emit('PageChange', 'Device')
                    }
                })
        }
    },
    persist: {
        debug: true,
        storage: sessionStorage,
        paths: [
            'selectedKeys', 'department', 'id', 'illArea',
            'deviceOptions', 'deviceVersionOptions', 'versionOptions',
            'SelfDeviceOptions', 'FirstValueData',
            'FirstData', 'SecondData', 'ThirdData',
            'SecondLeafArr', 'ThirdLeafArr',
            'currentPermissionLeafArr', 'deviceTypeOptions'
        ]
    }
})